import { PageHeader, PageHeaderNew } from "@/components";
import { Form, Input, Toast} from "antd-mobile";
import { Spin } from "antd";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { eventApplication, eventRegistration } from "../service";
interface personalImforIn {
  phone: string;
  card: string;
  name: string; //位置
}
export default function ApplicationPage() {
  const navigate = useNavigate();
  const [pageType, setPageType] = useState<string>();
  const [articleId, setArticleId] = useState<string>();
  const [personalImfor, setPersonalImfor] = useState<personalImforIn>()
  const [form] = Form.useForm();
  const [loaing, setLoaing] = useState(false);
  const onFinish =async (values: any) => {
    console.log(values, articleId,"提交");
    try {
      const { success } = await eventRegistration({
        activityId:articleId,
        villageCode: "511602006004" });
      if (!success) {
        Toast.show({
          icon: "fail",
          content: "报名失败",
        });
        setLoaing(false);
        return;
      }
      if (success) {
        setLoaing(false);
        Toast.show({
          icon: "success",
          content: "报名成功",
        });
        navigate(`/communityActivities?type=${pageType}`);
      }
    } catch (err) {
      console.error(err);
    }
  };
  useEffect(() => {
    const [type, id] = location?.search?.substring(1).split("&")
    setArticleId(id.split("=")?.[1]);
    setPageType(type.split("=")?.[1])
  }, [])

  useEffect(() => {
    // 查询用户个人信息
    eventApplication({ villageCode: "511602006004" })
      .then((res) => {
        if (res.code == 200) {
          setPersonalImfor(res.data);
        } else {
          console.log(res.data);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }, [])

  return (
    <Spin tip="提交中..." spinning={loaing}>
    <div className="ap_contarnier">
      <div className="header-bg"></div>
      <PageHeaderNew
        title="活动报名"
        goBack={() => navigate(`/communityActivities?type=${pageType}`)}
      />
      {personalImfor?.name ? <div className="ap_content eventFrom">
        <Form
          form={form}
          onFinish={onFinish}
          disabled={true}
          initialValues={{
            name: personalImfor?.name,
            id: personalImfor?.card,
            phone: personalImfor?.phone,
          }}
        >
          <Form.Item name="name" label="姓名">
            <Input />
          </Form.Item>
          <Form.Item name="id" label="身份证">
            <Input />
          </Form.Item>
          <Form.Item name="phone" label="联系电话">
            <Input />
          </Form.Item>
        </Form>
        <div className="ad_application ad_sure" onClick={() => form.submit()}>
          确定
        </div>
      </div> : null}

    </div>
    </Spin>
  );
}
